<template>
  <el-container class="bigbox">
    <el-header>
      <img src="../../image/study.jpg">
      <span>微服务卷B</span>
    </el-header>
    <el-container>
      <!-- 左侧 -->
      <el-aside style="position: relative;"></el-aside>

      <!-- 右侧 -->
      <el-main>
        <div class="fromBox">
          <div class="signup_div">
            <span class="signup-btn" :class="{'bottom': bottom.active}" id="signup_btn" @click="signupBtn">登录</span>
            <span class="line">|</span>
            <span class="signdown-btn" :class="{'bottom': !bottom.active}" id="signdown_btn" @click="signdownBtn">注册</span>
          </div>
          <!-- 登录表单 -->
          <el-form v-if="signupOrSigndown" ref="loginRefForm" :model="user" label-width="100px" :rules="loginRules">
            <el-form-item label="账号" prop="username">
              <el-input v-model="user.username" placeholder="4到16位(字母,数字,下划线,减号)" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="user.password" placeholder="6到18位数字" />
            </el-form-item>
            <el-form-item>
              <el-button class="signupBtn" type="primary" @click="login">登录</el-button>
            </el-form-item>
          </el-form>
          <!-- 注册表单 -->
          <el-form v-else ref="loginRefForm" :model="userSignIn" class="signUp" label-width="100px" :rules="signInRules">
            <el-form-item label="用户名：" prop="username">
              <el-input v-model="userSignIn.username" placeholder="4到16位(字母,数字,下划线,减号)" />
            </el-form-item>
            <el-form-item label="密码：" prop="password">
              <el-input v-model="userSignIn.password" type="password" placeholder="6到18位数字" />
            </el-form-item>
            <el-form-item label="确认密码：" prop="passwordAgain">
              <el-input v-model="userSignIn.passwordAgain" type="password" placeholder="请再次输入密码" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="signDownBtn" @click="signIn">注册</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive } from 'vue';
import { doGet, doPost } from "../../http/httpUserRequest.js";
import { getTokenName, messageTip, removeToken } from "../../util/util.js";

// 控制显示登录或注册表单
let signupOrSigndown = ref(true);
let bottom = reactive({ active: true });
let user = reactive({});
let userSignIn = reactive({ username: '', password: '', passwordAgain: "" });

let loginRules = {
  username: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入登录密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' }
  ],
};

let signInRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 16, message: '用户名长度应在4到16个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 18, message: '密码长度应在6到18个字符之间', trigger: 'blur' }
  ],
  passwordAgain: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: checkPasswordAgain, trigger: 'blur' }
  ],
};

const instance = getCurrentInstance();

onMounted(() => {
  freeLogin();
});

// 确认密码是否一致
function checkPasswordAgain(rule, value, callback) {
  if (value !== userSignIn.password) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
}

// 登录、注册按钮切换
function signupBtn() {
  bottom.active = true;
  signupOrSigndown = true;
};

function signdownBtn() {
  bottom.active = false;
  signupOrSigndown = false;
};

// 注册
function signIn() {
  if (!instance) return;
  instance.refs.loginRefForm.validate(isValid => {
    if (isValid) {
      let formData = new FormData();
      formData.append("username", userSignIn.username);
      formData.append("password", userSignIn.password);
      doPost("/user/signIn", formData).then(resp => {
        if (resp.data.code === 200) {
          messageTip("注册成功", "success");
          removeToken();
          window.location.href = "/";
        } else {
          messageTip("注册失败", "error");
        }
      });
    }
  });
};

// 登录
function login() {
  if (!instance) return;
  instance.refs.loginRefForm.validate(isValid => {
    if (isValid) {
      let formData = new FormData();
      formData.append("username", user.username);
      formData.append("password", user.password);
      doPost("/user/login", formData).then(resp => {
        if (resp.data.code === 200) {
          messageTip("登录成功", "success");
          removeToken();
          window.location.href = "/dashboard";
        } else {
          messageTip("登录失败", "error");
        }
      });
    }
  });
};

// 免登录验证
function freeLogin() {
  let token = window.localStorage.getItem(getTokenName());
  if (token) {
    doGet("/user/login/free", {}).then(resp => {
      if (resp.data.code === 200) {
        window.location.href = "/dashboard";
      }
    });
  }
};
</script>

<style scoped>
/* 样式保持原样，已优化代码部分 */
</style>
